import { useRoutes } from "react-router-dom";
import { Spin } from "antd"
import { Suspense, useContext } from 'react';
import { routeList } from "./routes";
import AuthRoute from './AuthRoute';
import { userContext } from "@/store/userContext";
import _ from 'lodash'
// 使用异步组件包裹路由文件，且符合条件的才可以加载
routeList.forEach(item => {
    item.element = <Suspense fallback={<Spin spinning={'页面加载中...'} />}>
        <AuthRoute auth={item.meta?.requiresAuth} title={item.meta?.title}>
            {item.element}
        </AuthRoute>
    </Suspense>
    if (item.children && item.children.length > 0) {
        item.children.forEach(sub => {
            sub.element = <Suspense fallback={<Spin spinning={'页面加载中...'} />}>
                <AuthRoute auth={sub.meta?.requiresAuth} title={sub.meta?.title}>
                    {sub.element}
                </AuthRoute>
            </Suspense>

        })
    }

})
// 默认面包屑
const home = [{
  path: '/index/home',
  name: '首页'
}]
const Routes = () => {
    let route = useRoutes(routeList)
    const context = useContext(userContext) as any
    let matches = route.props.routeContext.outlet?.props.routeContext.matches
    if (matches) {
        let nMatches = matches.map((item: any) => ({ path: item.route.meta.key, name:item.route.meta.title }))  
        window.sessionStorage.setItem('matches', JSON.stringify(_.uniqBy([...home,...nMatches], 'name'))) 
    }
     
    return route
}

export default Routes